// Declaring valid date character, minimum year and maximum year
// Declaring valid date character, minimum year and maximum year
/*---------------Lay Url--------------------------------------*/
function getBaseURL () 
{
	return location.protocol + "//" + location.hostname + 
	(location.port && ":" + location.port) + "/DemoPhp/";
}
/*---------------Lay Url--------------------------------------*/
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31;
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30;}
		if (i==2) {this[i] = 29;}
   } 
   return this;
}
//Ham kiem tra tinh hop le cua ngay thang nam
function isDate(dtStr){
	var daysInMonth = DaysArray(12);
	
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strDay=dtStr.substring(0,pos1);
	var strMonth=dtStr.substring(pos1+1,pos2);
	
	var strYear=dtStr.substring(pos2+1);
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
	}
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	if (pos1==-1 || pos2==-1){
		jQuery.showErr("Hay nhap dinh dang ngay hop le: dd/mm/yyyy \n (The date format should be : dd/mm/yyyy)");
		//alert("Hay nhap dinh dang ngay hop le: dd/mm/yyyy \n (The date format should be : dd/mm/yyyy)" )
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Nhap lai thang: 01-12  \n (Please enter a valid month)")
		jQuery.showErr("Nhap lai thang: 01-12  \n (Please enter a valid month)");
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		jQuery.showErr("Hay nhap ngay hop le. \n (Please enter a valid day)");
		return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		jQuery.showErr("Hay nhap nam hop le giua "+minYear+" va "+maxYear+" \n (Please enter a valid 4 digit year between "+minYear+" and "+maxYear+")");
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		jQuery.showErr("Hay nhap ngay hop le \n (Please enter a valid date)");
		return false;
	}
	return true;
}

var errHideTimeOut;
jQuery(window).scroll(function(){
	if(jQuery("#sysmsg-error") != "none" || jQuery("#sysmsg-success") != "none")
	{
		var top = jQuery.getBodyScrollTop();
		if(top < 157)
			top = 157;
		jQuery("#sysmsg-error-box").stop();
		jQuery("#sysmsg-error-box").animate({"top":top},{duration:300}); 
	}
});

jQuery.maxZIndex = jQuery.fn.maxZIndex = function(opt) 
{
    var def = { inc: 10, group: "*" };
    jQuery.extend(def, opt);    
    var zmax = 0;
    jQuery(def.group).each(function() {
        var cur = parseInt(jQuery(this).css('z-index'));
        zmax = cur > zmax ? cur : zmax;
    });
    if (!this.jquery)
        return zmax;

    return this.each(function() {
        zmax += def.inc;
        jQuery(this).css("z-index", zmax);
    });
}

jQuery.showErr = function(str)
{
	var top = jQuery.getBodyScrollTop();
	//if(top < 157)
		//top = 0;
		//jQuery("#divDialog").maxZIndex({ inc: 5 });
	    
	    // Get the zIndex as a number
	 var zindex=jQuery.maxZIndex()+1;
	jQuery("#sysmsg-error-box").css({"top":top});
	//jQuery("#sysmsg-error-box").css("z-index","100");
	//jQuery("#sysmsg-error-box").css("z-index",'"'+zindex+'"');
	document.getElementById("sysmsg-error-box").style.zIndex = zindex;
	jQuery("#sysmsg-error span:first").html(str);
	jQuery("#sysmsg-error").show();
	jQuery("#sysmsg-error-box").show();
	clearTimeout(errHideTimeOut);
	
	var hideErr = function(){
		jQuery("#sysmsg-error-box").slideUp(300);
	};
	
	errHideTimeOut = setTimeout(hideErr,5000);
	
	jQuery("#sysmsg-error-box .close").one("click", function(){
		jQuery("#sysmsg-error-box").hide();
	});
}

var successHideTimeOut;
jQuery.showSuccess = function(str)
{
	var top = jQuery.getBodyScrollTop();
	if(top < 157)
		top = 157;
	jQuery("#sysmsg-error-box").css({"top":top});
	jQuery("#sysmsg-success span:first").html(str);
	jQuery("#sysmsg-success").show();
	jQuery("#sysmsg-error").hide();
	jQuery("#sysmsg-error-box").show();
	
	clearTimeout(successHideTimeOut);
	
	var hideSuccess = function(){
		jQuery("#sysmsg-error-box").slideUp(300);
	};
	
	successHideTimeOut = setTimeout(hideSuccess,5000);
	
	jQuery("#sysmsg-error-box .close").one("click", function(){
		jQuery("#sysmsg-error-box").hide();
	});
}

jQuery.getBodyScrollTop=function(){
    var scrollPos; 
    if (typeof window.pageYOffset != 'undefined') { 
        scrollPos = window.pageYOffset; 
    } 
    else if (typeof document.compatMode != 'undefined' && 
        document.compatMode != 'BackCompat') { 
        scrollPos = document.documentElement.scrollTop; 
    } 
    else if (typeof document.body != 'undefined') { 
        scrollPos = document.body.scrollTop; 
    } 
    return scrollPos;
}


jQuery.minLength = function(value, length , isByte) {
	var strLength = jQuery.trim(value).length;
	if(isByte)
		strLength = jQuery.getStringLength(value);
		
	return strLength >= length;
};

jQuery.maxLength = function(value, length , isByte) {
	var strLength = jQuery.trim(value).length;
	if(isByte)
		strLength = jQuery.getStringLength(value);
		
	return strLength <= length;
};
jQuery.getStringLength=function(str)
{
	str = jQuery.trim(str);
	
	if(str=="")
		return 0; 
		
	var length=0; 
	for(var i=0;i <str.length;i++) 
	{ 
		if(str.charCodeAt(i)>255)
			length+=2; 
		else
			length++; 
	}
	
	return length;
}
//So sanh date
function IsDateGreater(DateValue1, DateValue2)
{
	//10/20/2010
	var array1=DateValue1.split("/");
	var array2=DateValue2.split("/");
	var value01=array1[2]+''+array1[1]+''+array1[0];
	var value02=array2[2]+''+array2[1]+''+array2[0];
	var num01 = new Number(value01);
	var num02 = new Number(value02);
	if(num01<num02)
		return false;
	else
		return true;
}

function IsDateLess(DateValue1, DateValue2)
{
	var DaysDiff;
	Date1 = new Date(DateValue1);
	Date2 = new Date(DateValue2);
	DaysDiff = Math.floor((Date1.getTime() - Date2.getTime())/(1000*60*60*24));
	//alert("DaysDiff ="+DaysDiff);
	if(DaysDiff <= 0)
	return true;
	else
	return false;
}

function IsDateEqual(DateValue1, DateValue2)
{
	var DaysDiff;
	Date1 = new Date(DateValue1);
	Date2 = new Date(DateValue2);
	DaysDiff = Math.floor((Date1.getTime() - Date2.getTime())/(1000*60*60*24));
	if(DaysDiff == 0)
	return true;
	else
	return false;
}




jQuery.checkEmail = function(val){
	var reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+jQuery/; 
	return reg.test(val);
};


function add_cart(id,attr)
{
	var ajaxurl = APP_ROOT+"/cart.php?act=addcart&id="+id;
	if(attr != '')
		ajaxurl += attr;
	jQuery.ajax({ 
		url: ajaxurl,
		dataType: "json",
		success: function(obj){
			if(obj.open_win == 1)
			{
				jQuery.weeboxs.open(obj.html, {contentType:'text',showButton:false,title:LANG['SELECT_AND_ADDCART'],width:550});
			}
			else if(obj.open_win == 2)
			{
				jQuery.showErr(obj.info);
			}
			else
			{
				location.href = CART_URL;
			}
		},
		error:function(ajaxobj)
		{
			alert(ajaxobj.responseText);
		}
	});
	
}

function del_cart(id)
{
	var ajaxurl = APP_ROOT+"/cart.php?act=delcart&id="+id;
	jQuery.ajax({ 
		url: ajaxurl,
		dataType: "json",
		success: function(obj){
			if(obj.status == 1)
			{
				jQuery("#cart_list").html(obj.html);
			}
			else
			{
				location.href = CART_URL;
			}
		},
		error:function(ajaxobj)
		{
			alert(ajaxobj.responseText);
		}
	});
}

function modify_cart(id,htmlobj)
{
	var number = jQuery(htmlobj).val();
	var ajaxurl = APP_ROOT+"/cart.php?act=modifycart&id="+id+"&number="+number;
	jQuery.ajax({ 
		url: ajaxurl,
		dataType: "json",
		success: function(obj){
			if(obj.status == 1)
			{
				jQuery("#cart_list").html(obj.html);
			}
			else
			{
				jQuery.showErr(obj.info);
			}
		},
		error:function(ajaxobj)
		{
			alert(ajaxobj.responseText);
		}
	});	
}

function submit_cart()
{
	var ajaxurl = APP_ROOT+"/cart.php?act=check&ajax=1";
	jQuery.ajax({ 
		url: ajaxurl,
		dataType: "json",
		success: function(obj){
			if(obj.status == 1)
			{
				location.href = CART_CHECK_URL;
			}
			else
			{
				jQuery.showErr(obj.info);
			}
		},
		error:function(ajaxobj)
		{
			alert(ajaxobj.responseText);
		}
	});		
}


jQuery.copyText = function(id)
{
	var txt = jQuery(id).val();
	if(window.clipboardData)
	{
		window.clipboardData.clearData();
		var judge = window.clipboardData.setData("Text", txt);
		if(judge === true)
			alert(LANG.JS_COPY_SUCCESS);
		else
			alert(LANG.JS_COPY_NOT_SUCCESS);
	}
	else if(navigator.userAgent.indexOf("Opera") != -1)
	{
		window.location = txt;
	} 
	else if (window.netscape) 
	{
		try
		{
			netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
		}
		catch(e)
		{
			alert(LANG.JS_NO_ALLOW);
		}
		var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
		if (!clip)
			return;
		var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
		if (!trans)
			return;
		trans.addDataFlavor('text/unicode');
		var str = new Object();
		var len = new Object();
		var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
		var copytext = txt;
		str.data = copytext;
		trans.setTransferData("text/unicode",str,copytext.length*2);
		var clipid = Components.interfaces.nsIClipboard;
		if (!clip)
			return false;
		clip.setData(trans,null,clipid.kGlobalClipboard);
		alert(LANG.JS_COPY_SUCCESS);
	}
};


function submit_mail(o)
{	
	var email = jQuery(o).parent("td").parent("tr").find("input[name='email']").val();
	if(email == '')
	{
		jQuery.showErr(LANG.EMAIL_EMPTY_TIP);
		return;
	}
	if(!jQuery.checkEmail(email))
	{
		jQuery.showErr(LANG.EMAIL_FORMAT_ERROR_TIP);
		return;
	}
	var ajaxurl = APP_ROOT+"/subscribe.php?act=addmail&email="+email+"&ajax=1";
	jQuery.ajax({ 
		url: ajaxurl,
		dataType: "json",
		success: function(obj){
			if(obj.status == 1)
			{
				jQuery.showSuccess(LANG.SUBSCRIBE_SUCCESS);
				return;
			}
			else
			{
				jQuery.showErr(obj.info);
				return;
			}
		},
		error:function(ajaxobj)
		{
			alert(ajaxobj.responseText);
		}
	});	
}


function load_consignee(consignee_id)
{
	var ajaxurl = APP_ROOT+"/ajax.php?act=load_consignee&id="+consignee_id;
	jQuery.ajax({ 
		url: ajaxurl,
		success: function(html){
			jQuery("#cart_consignee").html(html);
			load_delivery();
		},
		error:function(ajaxobj)
		{
			alert(LANG['REFRESH_TOO_FAST']);
		}
	});	
}


function load_delivery()
{
	var select_last_node = jQuery("#cart_consignee").find("select[value!='0']");
	if(select_last_node.length>0)
	{		
		var region_id = jQuery(select_last_node[select_last_node.length - 1]).val();
	}
	else
	{
		var region_id = 0;
	}
	
	var ajaxurl = APP_ROOT+"/ajax.php?act=load_delivery&id="+region_id;
	jQuery.ajax({ 
		url: ajaxurl,
		success: function(html){
			jQuery("#cart_delivery").html(html);
			count_buy_total();  
		},
		error:function(ajaxobj)
		{
			alert(LANG['REFRESH_TOO_FAST']);
		}
	});	
}


function count_buy_total()
{
	jQuery("#order_done").attr("disabled",true);
	var query = new Object();
	

	var delivery_id = jQuery("input[name='delivery']:checked").val();

	if(!delivery_id)
	{
		delivery_id = 0;
	}
	query.delivery_id = delivery_id;

	
	var select_last_node = jQuery("#cart_consignee").find("select[value!='0']");
	if(select_last_node.length>0)
	{		
		var region_id = jQuery(select_last_node[select_last_node.length - 1]).val();
	}
	else
	{
		var region_id = 0;
	}
	query.region_id = region_id;
	
	
	var account_money = jQuery("input[name='account_money']").val();
	if(!account_money||jQuery.trim(account_money)=='')
	{
		account_money = 0;
	}
	query.account_money = account_money;
	

	if(jQuery("#check-all-money").attr("checked"))
	{
		query.all_account_money = 1;
	}
	else
	{
		query.all_account_money = 0;
	}
	

	var ecvsn = jQuery("input[name='ecvsn']").val();
	if(!ecvsn)
	{
		ecvsn = '';
	}
	var ecvpassword = jQuery("input[name='ecvpassword']").val();
	if(!ecvpassword)
	{
		ecvpassword = '';
	}
	query.ecvsn = ecvsn;
	query.ecvpassword = ecvpassword;
	

	var payment = jQuery("input[name='payment']:checked").val();
	if(!payment)
	{
		payment = 0;
	}
	query.payment = payment;
	
	if(!isNaN(order_id)&&order_id>0)
	var ajaxurl = APP_ROOT+"/ajax.php?act=count_order_total&id="+order_id;
	else
	var ajaxurl = APP_ROOT+"/ajax.php?act=count_buy_total";
	jQuery.ajax({ 
		url: ajaxurl,
		data:query,
		type: "POST",
		dataType: "json",
		success: function(data){
			jQuery("#cart_total").html(data.html);
			jQuery("input[name='account_money']").val(data.account_money);
			if(data.pay_price == 0)
			{
				jQuery("input[name='payment']").attr("checked",false);
			}
			jQuery("#order_done").attr("disabled",false);
		},
		error:function(ajaxobj)
		{
			alert(LANG['REFRESH_TOO_FAST']);
		}
	});	
}



function submit_buy()
{
	jQuery("#order_done").attr("disabled",true);
	var query = new Object();
	

	var delivery_id = jQuery("input[name='delivery']:checked").val();

	if(!delivery_id)
	{
		delivery_id = 0;
	}
	query.delivery_id = delivery_id;


	var select_last_node = jQuery("#cart_consignee").find("select[value!='0']");
	if(select_last_node.length>0)
	{		
		var region_id = jQuery(select_last_node[select_last_node.length - 1]).val();
	}
	else
	{
		var region_id = 0;
	}
	query.region_id = region_id;
	

	var account_money = jQuery("input[name='account_money']").val();
	if(!account_money||jQuery.trim(account_money)=='')
	{
		account_money = 0;
	}
	query.account_money = account_money;
	

	if(jQuery("#check-all-money").attr("checked"))
	{
		query.all_account_money = 1;
	}
	else
	{
		query.all_account_money = 0;
	}
	

	var ecvsn = jQuery("input[name='ecvsn']").val();
	if(!ecvsn)
	{
		ecvsn = '';
	}
	var ecvpassword = jQuery("input[name='ecvpassword']").val();
	if(!ecvpassword)
	{
		ecvpassword = '';
	}
	query.ecvsn = ecvsn;
	query.ecvpassword = ecvpassword;
	
	
	var payment = jQuery("input[name='payment']:checked").val();
	if(!payment)
	{
		payment = 0;
	}
	query.payment = payment;
	
	if(!isNaN(order_id)&&order_id>0)
	var ajaxurl = APP_ROOT+"/ajax.php?act=count_order_total&id="+order_id;
	else
	var ajaxurl = APP_ROOT+"/ajax.php?act=count_buy_total";
	jQuery.ajax({ 
		url: ajaxurl,
		data:query,
		type: "POST",
		dataType: "json",
		success: function(data){
			if(data.is_delivery == 1)
			{
			
				if(!data.region_info||data.region_info.region_level != 4)
				{
					jQuery.showErr(LANG['FILL_CORRECT_CONSIGNEE_ADDRESS']);
					jQuery("#order_done").attr("disabled",false);
					return;
				}
				if(jQuery.trim(jQuery("input[name='consignee']").val())=='')
				{
					jQuery.showErr(LANG['FILL_CORRECT_CONSIGNEE']);
					jQuery("#order_done").attr("disabled",false);
					return;
				}
				if(jQuery.trim(jQuery("input[name='address']").val())=='')
				{
					jQuery.showErr(LANG['FILL_CORRECT_ADDRESS']);
					jQuery("#order_done").attr("disabled",false);
					return;
				}
				if(jQuery.trim(jQuery("input[name='zip']").val())=='')
				{
					jQuery.showErr(LANG['FILL_CORRECT_ZIP']);
					jQuery("#order_done").attr("disabled",false);
					return;
				}
				if(jQuery.trim(jQuery("input[name='mobile']").val())=='')
				{
					jQuery.showErr(LANG['FILL_MOBILE_PHONE']);
					jQuery("#order_done").attr("disabled",false);
					return;
				}
				if(!jQuery.checkMobilePhone(jQuery("input[name='mobile']").val()))
				{
					jQuery.showErr(LANG['FILL_CORRECT_MOBILE_PHONE']);
					jQuery("#order_done").attr("disabled",false);
					return;
				}
				if(!data.delivery_info)
				{
					jQuery.showErr(LANG['PLEASE_SELECT_DELIVERY']);
					jQuery("#order_done").attr("disabled",false);
					return;
				}			
			}
			
			if(data.pay_price!=0&&!data.payment_info)
			{
				jQuery.showErr(LANG['PLEASE_SELECT_PAYMENT']);
				jQuery("#order_done").attr("disabled",false);
				return;
			}	
			
			jQuery("#cart_form").submit();
		},
		error:function(ajaxobj)
		{			
			alert("error: "+ajaxobj.responseText);
			return false;
		}
	});	
}

function submit_sms()
{
	jQuery.weeboxs.open(APP_ROOT+"/sms.php?act=subscribe", {contentType:'ajax',showButton:false,title:LANG['SMS_SUBSCRIBE'],width:400,height:200});	
}
function unsubmit_sms()
{
	jQuery.weeboxs.open(APP_ROOT+"/sms.php?act=unsubscribe", {contentType:'ajax',showButton:false,title:LANG['SMS_UNSUBSCRIBE'],width:400,height:200});	
}



function check_coupon()
{
	var coupon_sn = jQuery.trim(jQuery("#coupon_sn").val());
	var ajaxurl = APP_ROOT+"/coupon.php?act=check_coupon&coupon_sn="+coupon_sn;
	jQuery.ajax({ 
		url: ajaxurl,
		success: function(msg){
			alert(msg);
		},
		error:function(ajaxobj)
		{
			alert(ajaxobj.responseText);
		}
	});	
}

function use_coupon()
{
	var coupon_sn = jQuery.trim(jQuery("#coupon_sn").val());
	var coupon_pwd = jQuery.trim(jQuery("#coupon_pwd").val());
	var ajaxurl = APP_ROOT+"/coupon.php?act=use_coupon&coupon_sn="+coupon_sn+"&coupon_pwd="+coupon_pwd;
	jQuery.ajax({ 
		url: ajaxurl,
		dataType: "json",
		success: function(obj){
			if(obj.status==2)
			{
				jQuery.weeboxs.open(APP_ROOT+"/coupon.php?act=ajax_supplier_login", {contentType:'ajax',showButton:false,title:LANG['SUPPLIER_LOGIN'],width:500,height:150});	
			}
			if(obj.status == 0)
			{
				
				alert(obj.msg);
			}
			if(obj.status == 1)
			{
				
				alert(obj.msg);
			}
		},
		error:function(ajaxobj)
		{
			alert(ajaxobj.responseText);
		}
	});
}
/*-------Cong ngay-------------*/
function addDays(myDateString,days) 
{
	//myDateString='dd/mm/yyyy'
	var arr=myDateString.split("/");
	var d = new Date(arr[2],arr[1]-1,arr[0]);
    d.setDate(d.getDate() + days);
    var date = d.getDate();
    var month = d.getMonth()+1;
    var year = d.getFullYear();
	date = (date < 10) ? '0' + date : date;
	month = (month< 10) ? '0' + month :month;
		 // year = (year < 1000) ? year + 1900 : year;
    return (date+'/'+month +'/'+year);
}
/*-------Tru ngay-------------*/
function minusDays(myDateGiatri,myDateGD) 
{
	var arr1=myDateGiatri.split("/");
	var d1 = new Date(arr1[2],arr1[1]-1,arr1[0]);
	
	var arr2=myDateGD.split("/");
	var d2 = new Date(arr2[2],arr2[1]-1,arr2[0]);
	var one_day=1000*60*60*24;
	var ret=Math.ceil((d1.getTime()-d2.getTime())/(one_day));
	return ret;
}
function compare2Date(myDateGiatri,myDateGD) 
{
	var arr1=myDateGiatri.split("/");
	var d1 = new Date(arr1[2],arr1[1]-1,arr1[0]);
	
	var arr2=myDateGD.split("/");
	var d2 = new Date(arr2[2],arr2[1]-1,arr2[0]);
	var one_day=1000*60*60*24;
	var ret=Math.ceil((d1.getTime()-d2.getTime())/(one_day));
	return ret;
}
function numberOnly(e) {
	var unicode=e.charCode? e.charCode : e.keyCode;
	if (unicode!=8){ //if the key isn't the backspace key (which we should allow)
	if (unicode<48||unicode>57) return false; //if not a number return false //disable key press
	}} 
function numberCurr(obj)
{
	var strVal=jQuery(this).val();
	var strVal = strVal.replace(/[^.,0-9]+/g,"");
	jQuery(this).val(strVal);
}
/*-------------Kiem tra trang thai truoc khi thay doi-----------------*/
function checkStatus(control)
{	
	if(control=='create')//them moi
	 return true;
	var id = jQuery("#TradingList").jqGrid('getGridParam','selrow'); 
		var obj;
		if (id) 
		{ 
			var obj = jQuery("#TradingList").jqGrid('getRowData',id);
			
			//save,push_approve,approve,cancel_approve,reject_approve,del
			
			if(obj.trangthai=='-1')
			{
				if(control=='save'||control=='del'||control=='view')
					return true;
				else
				{
					jQuery.showErr('Ban khong the thao tac ban ghi nay vi no dang o trang thai: <blink>Dien moi</blink>');
					return false;
				}
			}
				
			
			if(control=='save'||control=='push_approve'||control=='del')//thay doi - day duyet -xoa
			{	
				if(obj.trangthai=='0'||obj.trangthai=='4')
				{
					return true;
				}else
				{
					jQuery.showErr('Ban khong the thao tac ban ghi nay vi no dang o trang thai: <blink>'+obj.trangthai_display +'</blink>');
					return false;
				}	
			}
			if(control=='approve'||control=='reject_approve')//duyet- tuchoi
			{
				if(obj.trangthai=='1')
				{
					return true;
				}else
				{
					jQuery.showErr('Ban khong the thao tac ban ghi nay vi no dang o trang thai: <blink>'+obj.trangthai_display +'</blink>');
					return false;
				}	
			}
			if(control=='cancel_approve')//huy duyet
			{
				if(obj.trangthai=='2')
				{
					return true;
				}else
				{
					jQuery.showErr('Ban khong the thao tac ban ghi nay vi no dang o trang thai: <blink>'+obj.trangthai_display +'</blink>');
					return false;
				}	
			}
			return true;
				
		}else
		{
			jQuery.showErr('Xin vui long chon 1 ban ghi de thao tac!');
			return false;
		}
}

function checkStatusUpdate(control, rowSelect)
{	
	if(control=='create')//them moi
	 return true;	
		var obj;
		var obj = jQuery("#TradingList").jqGrid('getRowData',rowSelect);
		
		//save,push_approve,approve,cancel_approve,reject_approve,del
		
		if(obj.trangthai=='-1')
		{
			if(control=='save'||control=='del'||control=='view')
				return true;
			else
			{
				jQuery.showErr('Ban khong the thao tac ban ghi nay vi no dang o trang thai: <blink>Dien moi</blink>');
				return false;
			}
		}
			
		
		if(control=='save'||control=='push_approve'||control=='del')//thay doi - day duyet -xoa
		{	
			if(obj.trangthai=='0'||obj.trangthai=='4')
			{
				return true;
			}else
			{
				jQuery.showErr('Ban khong the thao tac ban ghi nay vi no dang o trang thai: <blink>'+obj.trangthai_display +'</blink>');
				return false;
			}	
		}
		if(control=='approve'||control=='reject_approve')//duyet- tuchoi
		{
			if(obj.trangthai=='1')
			{
				return true;
			}else
			{
				jQuery.showErr('Ban khong the thao tac ban ghi nay vi no dang o trang thai: <blink>'+obj.trangthai_display +'</blink>');
				return false;
			}	
		}
		if(control=='cancel_approve')//huy duyet
		{
			if(obj.trangthai=='2')
			{
				return true;
			}else
			{
				jQuery.showErr('Ban khong the thao tac ban ghi nay vi no dang o trang thai: <blink>'+obj.trangthai_display +'</blink>');
				return false;
			}	
		}
		return false;	
}
	function jsonConcat(o1, o2) 
	{
		 for (var key in o2) {
		  o1[key] = o2[key];
		 }
		 return o1;
	}
	/*--------------------Start Random String -------------------------*/


	function randomString() {
		var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
		var string_length = 8;
		var randomstring = '';
		for (var i=0; i<string_length; i++) {
			var rnum = Math.floor(Math.random() * chars.length);
			randomstring += chars.substring(rnum,rnum+1);
		}
		return randomstring;
	}
	/*--------------------End Random String -------------------------*/


	/*--------------------Start get CaptCha---------------------------*/
	function getCaptCha()
	{
		jQuery.ajax({
			url: getBaseURL()+'user/process',
			dataType: "json",
			data:{act:'captcha',session:'true',key:randomString()},
			type: "POST",
			async: true,
			success: function(msg) 
			{
				if(msg.ret=='success')
				{
					 jQuery("#captcha").attr( 'src',msg.url );
				}
				else
				{
					jQuery("#captcha").attr( 'src','notFound' );
					return 'notFound';
				}	
			}
		});
	}
	
	/*--------------------End get CaptCha-----------------------------*/
	
	/*--------------------Start Exites Email---------------------------*/
	function emailExites(formName)
	{
		 var method={act:'email',session:'true',key:randomString()};
		   var myJSONtext=jQuery('#'+formName).toJSON();
		   var output = {};
			output = jsonConcat(output, myJSONtext);
			output = jsonConcat(output, method);
		jQuery.ajax({
			url: '../user/process',
			dataType: "json",
			data:output,
			type: "POST",
			async: true,
			success: function(msg) 
			{
				if(msg.ret=='success')
				{
					 jQuery("#email_edit").focus();
			    	 jQuery.showErr(" Địa chỉ email này đã tồn tại, Xin vui lòng nhập email khác!");
			    	 addToBasket('bee','email_edit');
			    	 return false;
				}
				
			}
		});
	}
	/*--------------------End Start Exites Email---------------------------*/
	
	
	/*-----------------------Doc tien--------------------------------------*/
	var ChuSo=new Array(" không "," một "," hai "," ba "," bốn "," năm "," sáu "," bảy "," tám "," chín ");
	var Tien=new Array( "", " nghìn", " triệu", " tỷ", " nghìn tỷ", " triệu tỷ");

	//1. Hàm đọc số có ba chữ số;
	function DocSo3ChuSo(baso)
	{

		var tram;
	    var chuc;
	    var donvi;
	    var KetQua="";
	    tram=parseInt(baso/100);
	    chuc=parseInt((baso%100)/10);
	    donvi=baso%10;
	    if(tram==0 && chuc==0 && donvi==0) return "";
	    if(tram!=0)
	    {
	        KetQua += ChuSo[tram] + " trăm ";
	        if ((chuc == 0) && (donvi != 0)) KetQua += " linh ";
	    }
	    if ((chuc != 0) && (chuc != 1))
	    {
	            KetQua += ChuSo[chuc] + " mươi";
	            if ((chuc == 0) && (donvi != 0)) KetQua = KetQua + " linh ";
	    }
	    if (chuc == 1) KetQua += " mười ";
	    switch (donvi)
	    {
	        case 1:
	            if ((chuc != 0) && (chuc != 1))
	            {
	                KetQua += " mốt ";
	            }
	            else
	            {
	                KetQua += ChuSo[donvi];
	            }
	            break;
	        case 5:
	            if (chuc == 0)
	            {
	                KetQua += ChuSo[donvi];
	            }
	            else
	            {
	                KetQua += " lăm ";
	            }
	            break;
	        default:
	            if (donvi != 0)
	            {
	                KetQua += ChuSo[donvi];
	            }
	            break;
	        }
	    return KetQua;
	}

	//2. Hàm đọc số thành chữ (Sử dụng hàm đọc số có ba chữ số)

	function DocTienBangChu(money)
	{
		var SoTien=money.replace(/,/g,'');
		var lan=0;
	    var i=0;
	    var so=0;
	    var KetQua="";
	    var tmp="";
	    var ViTri = new Array();
	    if(SoTien<0) return "Số tiền âm !";
	    if(SoTien==0) return "Không đồng !";
	    if(SoTien>0)
	    {
	        so=SoTien;
	    }
	    else
	    {
	        so = -SoTien;
	    }
	    if (SoTien > 8999999999999999)
	    {
	        //SoTien = 0;
	        return "Số quá lớn!";
	    }
	    ViTri[5] = Math.floor(so / 1000000000000000);
	    if(isNaN(ViTri[5]))
	        ViTri[5] = "0";
	    so = so - parseFloat(ViTri[5].toString()) * 1000000000000000;
	    ViTri[4] = Math.floor(so / 1000000000000);
	     if(isNaN(ViTri[4]))
	        ViTri[4] = "0";
	    so = so - parseFloat(ViTri[4].toString()) * 1000000000000;
	    ViTri[3] = Math.floor(so / 1000000000);
	     if(isNaN(ViTri[3]))
	        ViTri[3] = "0";
	    so = so - parseFloat(ViTri[3].toString()) * 1000000000;
	    ViTri[2] = parseInt(so / 1000000);
	     if(isNaN(ViTri[2]))
	        ViTri[2] = "0";
	    ViTri[1] = parseInt((so % 1000000) / 1000);
	     if(isNaN(ViTri[1]))
	        ViTri[1] = "0";
	    ViTri[0] = parseInt(so % 1000);
	  if(isNaN(ViTri[0]))
	        ViTri[0] = "0";
	    if (ViTri[5] > 0)
	    {
	        lan = 5;
	    }
	    else if (ViTri[4] > 0)
	    {
	        lan = 4;
	    }
	    else if (ViTri[3] > 0)
	    {
	        lan = 3;
	    }
	    else if (ViTri[2] > 0)
	    {
	        lan = 2;
	    }
	    else if (ViTri[1] > 0)
	    {
	        lan = 1;
	    }
	    else
	    {
	        lan = 0;
	    }
	    for (i = lan; i >= 0; i--)
	    {
	       tmp = DocSo3ChuSo(ViTri[i]);
	       KetQua += tmp;
	       if (ViTri[i] > 0) KetQua += Tien[i];
	       if ((i > 0) && (tmp.length > 0)) KetQua += ',';//&& (!string.IsNullOrEmpty(tmp))
	    }
	   if (KetQua.substring(KetQua.length - 1) == ',')
	   {
	        KetQua = KetQua.substring(0, KetQua.length - 1);
	   }
	   KetQua = KetQua.substring(1,2).toUpperCase()+ KetQua.substring(2);
	   if(KetQua!='')KetQua=KetQua+ " đồng";
	   return KetQua;//.substring(0, 1);//.toUpperCase();// + KetQua.substring(1);
	}
	
	/*-----------------------Ket thuc doc tien-----------------------------*/
